<?php

namespace app\service;

class AesService
{
    public static ?AesService $_instance = null;
    /*密钥,22个字符*/
    protected string $key = 'owenweb';
    /*向量，8个或10个字符*/
    protected string $iv = 'owenweb';

    /**
     * @return AesService|mixed
     */
    public static function instance(): ?AesService
    {
        if (!static::$_instance) static::$_instance = new self();
        return static::$_instance;
    }

    public function setkey(string $key): static
    {
        $this->key = $key;
        return $this;
    }

    public function getkey(): string
    {
        return $this->key;
    }

    public function getiv(): string
    {
        return $this->iv;
    }

    /**
     * 加密
     * AES/CBC/PKCS7Padding
     * AES加密：(https://www.mklab.cn/utils/aes)
     * 编码base64,模式CBC,填充Pkcs7Padding,位数128位,输入格式base64,输出格式string,
     * 字符集utf-8,密钥T3lUf3t3pdHzSx8U,偏移量cdccB3mtWDu7mcxw
     * (例如17055885566加密后Hh3PyHpjehubCOkcqUkmjA==)
     * (https://www.lddgo.net/encrypt/aes)
     *
     * @param boolean $status 是否加密
     *
     * @return string 处理过的数据
     */
    public function encrypt($data, bool $status = true): string
    {
        if (is_array($data)) $data = json_encode($data);
        $key = $this->getkey();
        $iv  = $this->getiv();
        if ($status) return base64_encode(openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv));
        return $data;
    }

    /**
     * 解密
     *
     * @return string 加密的字符串不是完整的会返回空字符串值
     */
    public function decrypt($data, bool $status = true): string
    {
        $key = $this->getkey();
        $iv  = $this->getiv();
        if ($status) return openssl_decrypt(base64_decode($data), 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return $data;
    }

}